package com.foundao.util.controller;

import cn.hutool.core.collection.CollUtil;
import com.tx.core.util.excel.PoiExcelExportUtil;
import com.tx.core.util.excel.PoiExcelImportUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @Package: com.foundao.util.controller
 * @ClassName: ExcelController
 * @Author: chenli
 * @CreateTime: 2021/7/28 2:22 下午
 * @Description:
 */
@Controller
@Slf4j
public class ExcelController {

    @GetMapping("/goUpload")
    public String upload() {
        return "uploadExcel";
    }

    @PostMapping("/mergeAndExport")
    @ResponseBody
    public void mergeAndExport(@RequestParam("file") MultipartFile[] file, HttpServletResponse response) throws Exception {
        log.info("解析excel，文件个数："+file.length);
        Map<String,Integer> map = new HashMap<>();
        for (MultipartFile f:file) {
            if (!f.getResource().getFilename().endsWith(".xlsx") && !f.getResource().getFilename().endsWith(".xls")) {
                throw new Exception("文件类型错误");
            }
            PoiExcelImportUtil poiExcelImportUtil = new PoiExcelImportUtil(f.getInputStream());
            List<Map<String, String>> list = poiExcelImportUtil.importExcelToMap(0, 2, 3);
            list.forEach(m->{
                String key = m.get("关键词");
                int points = Integer.parseInt(m.get("指数"));
                if (map.get(key)== null || points > map.get(key)) {
                    map.put(key,points);
                }
            });
        }
        Map<String, Integer> sortByValueMap = sortByValue(map);
        List<String> headers = Arrays.asList("关键字","指数");
        List<List<Object>> data = CollUtil.newArrayList();
        sortByValueMap.forEach((k,v)->{
            data.add(Arrays.asList(k,v));
        });
        PoiExcelExportUtil.exportExcelHTTP("关键字-指数",headers,data,response);
    }

    /**
     * map集合，按照value排列
     * @param maps
     * @param <K>
     * @param <V>
     * @return
     */
    public static  <K,V extends Comparable<? super V> > Map<K,V> sortByValue(Map<K,V> maps){
        Map<K,V> result = new LinkedHashMap<>();
        maps.entrySet().stream().
                sorted( Map.Entry.<K,V>comparingByValue().reversed() ).forEachOrdered(e-> result.put(e.getKey(),e.getValue()));
        return result;
    }
}
